package com.stanley.alogrithm.sorts;

import java.util.Arrays;

public class CounterSort {

    public static void main(String[] args) {
        int[] data = {1, 7, 12, 1, 8, 4, 7, 4, 2, 0, 2, 4, 6};
        CounterSort sort = new CounterSort(0, 12);
        sort.sort(data);
        System.out.println("result: " + Arrays.toString(data));
    }

    private int min;
    private int max;
    private int interval;

    public CounterSort(int minValue, int maxValue) {
        min = minValue;
        max = maxValue;
        interval = max - min;
    }

    public void sort(int[] array) {
        int[] counters = new int[interval + 1];

        for (int i = 0; i < array.length; i++) {
            int index = calcIndex(array[i]);
            counters[index]++;
        }

        int k = 0;
        for (int i = 0; i < counters.length; i++) {
            while (counters[i]-- > 0) {
                array[k++] = indexToValue(i);
            }
        }
    }

    private int calcIndex(int value) {
        return value - min;
    }

    private int indexToValue(int index) {
        return index + min;
    }
}
